package com.yuan.java.socket.niosocket;

import com.yuan.java.pack16.SocketPackUtils;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;

/**
 * @author yuaneg 2019/7/10
 */
public class SimpleNioClient {

    @Test
    public void nioClient() throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        SocketChannel socketChannel = null;
        try {
            int i = 0;
            while (true) {
                socketChannel = SocketChannel.open();
                socketChannel.configureBlocking(false);
                socketChannel.connect(new InetSocketAddress("10.1.1.18", 8001));
                if (socketChannel.finishConnect()) {
                    TimeUnit.SECONDS.sleep(1);
                    String info = "I'm " + i++ + "-th information from client";
                    buffer.clear();
                    buffer.put(info.getBytes());
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        System.out.println(SocketPackUtils.byteArr2HexStrBlank(info.getBytes()));
                        System.out.println(new  String(info.getBytes()));
                        socketChannel.write(buffer);
                    }
                    socketChannel.close();
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socketChannel != null) {
                    socketChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
